
#include "GameEngine.h"


IGameEngine* GameEngine::_gameEngine;

GameEngine::GameEngine() :
	loggingLevel(0)
{

	//Read in an integer from a txt file to
	//determine what level of error logging
	//should be done 0 thru 3, 0 being no error
	//messages
	std::ifstream inFile;
	inFile.open("../../res/LoggingLevel.txt");
	if(inFile.is_open())
	{
		inFile >> loggingLevel;
		inFile.close();
	}

	_gcList = new std::vector<IGameManager*>();
	_gcList->push_back(OgreManager::getSingleton());
	_gcList->push_back(InputManager::getSingleton());
	_gcList->push_back(ObjectManager::getSingleton());
	_gcList->push_back(StateManager::getSingleton());
	
	_running = false;
}

void GameEngine::Run(){
	if(_running)
		return;
	
	_running = true;

	Initialize();  //starts up ogre

	Cleanup();	//done...cleaning up
}
	
void GameEngine::ShutDown(){
	_running = false;
}

int GameEngine::GetLoggingLevel()
{
	return loggingLevel;
}

void GameEngine::Initialize(){	

	for(std::vector<IGameManager*>::iterator it = _gcList->begin(); it != _gcList->end(); it++){
		if(!_running)	//check for an engine shutdown call (cancel button in ogre window)
			return;	
		(*it)->Initialize();
	}

	GameServices::OgreManager()->GetCamera()->setPosition(0,0,15000);
	GameServices::OgreManager()->GetCamera()->lookAt(0,0,0);

	GameServices::OgreManager()->GetRoot()->addFrameListener(this);
	GameServices::OgreManager()->GetRoot()->startRendering();
}

bool GameEngine::frameStarted(const Ogre::FrameEvent& gameTime){
	for(std::vector<IGameManager*>::iterator it = _gcList->begin(); it != _gcList->end(); it++){
		(*it)->UpdateStarted(gameTime);
	}
	return _running;
}

bool GameEngine::frameEnded(const Ogre::FrameEvent& gameTime){
	for(std::vector<IGameManager*>::iterator it = _gcList->begin(); it != _gcList->end(); it++){
		(*it)->UpdateEnded(gameTime);
	}
	return _running;
}

void GameEngine::Cleanup(){
	GameServices::OgreManager()->GetRoot()->removeFrameListener(this);
	
	while(_gcList->begin() != _gcList->end()){
		_gcList->back()->Cleanup();
		delete _gcList->back();
		_gcList->erase(_gcList->end()-1);
	}
	delete _gcList;
}
